<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class ImportAndMigrate extends Command
{

    //php artisan import:exam E:\phpEnv\www\web\exam\public\data.xlsx

    protected $signature = 'import:exam {file}';


    public function handle()
    {
        ini_set('memory_limit', '-1');

        $file = $this->argument('file');

        $importPaperListByPaperId = DB::connection('test')->table('import')->pluck('id', 'paper_id')->toArray();

        // 使用 maatwebsite/excel 包来读取 Excel 文件
        $data = Excel::toCollection(null, $file);
        try {
            foreach ( $data as $key => $sheetData ) {

                try {
                    $insertData = [];
                    foreach ( $sheetData as $index => $item ) {
                        if ($index == 0) {
                            continue;
                        }
                        $paperId = $item[6] ?? null;
                        if (! $paperId) {
                            continue;
                        }
                        $paperId = str_replace("\n", "", $paperId);
                        if (! str_starts_with((string)$paperId, "2")) {
                            continue;
                        }
                        if (isset($importPaperListByPaperId[$paperId])) {
                            continue;
                        }
                        // if (! ctype_digit($item[2] ?? 0)) {
                        //     continue;
                        // }
                        $insertData[] = [
                            'paper_id'    => $paperId,
                            'sheet'       => $key,
                            'author'      => $item[3] ?? '',
                            // 'num'         => $item[2] ?? 0,
                            // 'title'       => $item[1] ?? '',
                            'create_time' => date('Y-m-d H:i:s', 1723133461)
                        ];
                    }
                    if (! $insertData) {
                        continue;
                    }
                    DB::connection('test')->table('import')->insert($insertData);
                    DB::commit();
                } catch (\Throwable $exception) {
                    $this->error('导入失败:'.$exception->getMessage());
                    DB::rollBack();
                }
            }

        } catch (\Throwable $exception) {
            $this->error('导入失败:'.$exception->getMessage());

            return;
        }
        $this->info('导入完成');
    }
}